package com.degon.hsyl.customchatapp.ui;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.degon.hsyl.customchatapp.R;
import com.degon.hsyl.customchatapp.adapter.HomeUserListAdapter;
import com.degon.hsyl.customchatapp.bean.Linkman;
import com.degon.hsyl.customchatapp.model.QiNiuTokenModel;
import com.degon.hsyl.customchatapp.model.RongYunTokenResponseModel;
import com.degon.hsyl.customchatapp.model.UploadImageResponseModel;
import com.degon.hsyl.customchatapp.util.DataUtil;
import com.degon.hsyl.customchatapp.util.HttpUtil;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.wildma.pictureselector.PictureBean;
import com.wildma.pictureselector.PictureSelector;

import org.litepal.LitePal;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private EditText userId;
    private EditText userName;
    private SimpleDraweeView uploadHeadPic;
    private String headPortrait = "";
    private RelativeLayout registerBtn;
    private RecyclerView userList;
    private List<Linkman> linkmen = new ArrayList<>();
    private HomeUserListAdapter adapter;

    private Handler handler;
    private String qiNiuYunToken = "";

    @SuppressLint("HandlerLeak")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //创建表
        SQLiteDatabase db = LitePal.getDatabase();

        initViews();

        handler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                if(msg.what == 1){
                    QiNiuTokenModel model = (QiNiuTokenModel) msg.obj;
                    qiNiuYunToken = model.getData().getToken();
                }else if(msg.what == 2){
                    UploadImageResponseModel model = (UploadImageResponseModel) msg.obj;
                    headPortrait = model.getData();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            uploadHeadPic.setImageURI(Uri.parse(headPortrait));
                        }
                    });
                }else if(msg.what == 3){
                    RongYunTokenResponseModel model = (RongYunTokenResponseModel) msg.obj;
                    Linkman linkman = new Linkman();
                    linkman.setHeadPortrait(headPortrait);
                    linkman.setUserId(model.getUserId());
                    linkman.setToken(model.getToken());
                    linkman.setName(userName.getText().toString());
                    linkman.saveThrows();
                    linkmen.add(linkman);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            adapter.notifyDataSetChanged();
                        }
                    });
                }
            }
        };

        getQiNiuYunToken();

        uploadHeadPic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(qiNiuYunToken.equals("")){
                    ToastUtils.showLong("网络初始化中,请稍后重试");
                }else {
                    PictureSelector
                            .create(MainActivity.this, PictureSelector.SELECT_REQUEST_CODE)
                            .selectPicture(true, 400, 400, 1, 1);
                }
            }
        });

        registerBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(userId.getText().toString().equals("") || userName.getText().toString().equals("") || headPortrait.equals("")){
                    ToastUtils.showShort("请先填写用户id、姓名及上传头像");
                }else if (isIdExist(userId.getText().toString())){
                    ToastUtils.showLong("用户id重复创建");
                }else{
                    registerUser();
                }
            }
        });

        linkmen =LitePal.findAll(Linkman.class);

        for(Linkman linkman : linkmen){
            LogUtils.i(linkman.getHeadPortrait());
            LogUtils.i(linkman.getName());
            LogUtils.i(linkman.getToken());
            LogUtils.i(linkman.getUserId());
        }

        adapter = new HomeUserListAdapter(linkmen, this);
        userList.setAdapter(adapter);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PictureSelector.SELECT_REQUEST_CODE) {
            if (data != null) {
                PictureBean pictureBean = data.getParcelableExtra(PictureSelector.PICTURE_RESULT);
                if(pictureBean.isCut()){
                    String path = pictureBean.getPath();
                    uploadHeadPic(path);
                }
            }
        }
    }

    private void registerUser(){
        String url = "https://api-cn.ronghub.com/user/getToken.json";
        RequestBody body = new FormBody.Builder()
                .add("userId", userId.getText().toString())
                .add("name", userName.getText().toString())
                .add("portraitUri", headPortrait)
                .build();
        new Thread(){
            @Override
            public void run() {
                try {
                    Response response = HttpUtil.rongYunPost(url, body);
                    RongYunTokenResponseModel model = new Gson().fromJson(response.body().string(), RongYunTokenResponseModel.class);
                    if(model.getCode() == 200){
                        Message message = new Message();
                        message.what = 3;
                        message.obj = model;
                        handler.handleMessage(message);
                    }else{
                        ToastUtils.showLong("会话服务器异常");
                    }
                }catch (IOException | NoSuchAlgorithmException e){
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private boolean isIdExist(String id){
        boolean result = false;
        if(linkmen.size() == 0){
            return result;
        }else{
            for(Linkman linkman : linkmen){
                if(linkman.getUserId().equals(id)){
                    result = true;
                    break;
                }
            }
        }
        return result;
    }

    private void uploadHeadPic(String path){
        String url = HttpUtil.yuMing + "/api/common/upload_img";
        String base64 = "data:image/jpg;base64," + DataUtil.ImageToBase64(path);
        RequestBody body = new FormBody.Builder()
                .add("img", base64)
                .build();
        new Thread(){
            @Override
            public void run() {
                try {
                    Response response = HttpUtil.postWithToken(url, body, qiNiuYunToken);
                    UploadImageResponseModel model = new Gson().fromJson(response.body().string(), UploadImageResponseModel.class);
                    if(model.getStatus() == 1){
                        ToastUtils.showLong(model.getMsg());
                        Message message = new Message();
                        message.what = 2;
                        message.obj = model;
                        handler.handleMessage(message);
                    }else{
                        ToastUtils.showShort(model.getMsg());
                    }
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private void getQiNiuYunToken(){
        String url = HttpUtil.yuMing + "/api/qiniu";
        new Thread(){
            @Override
            public void run() {
                try {
                    Response response = HttpUtil.get(url);
                    QiNiuTokenModel model = new Gson().fromJson(response.body().string(), QiNiuTokenModel.class);
                    if(model.getStatus() == 1){
                        Message message = new Message();
                        message.what = 1;
                        message.obj = model;
                        handler.handleMessage(message);
                    }else{
                        ToastUtils.showLong(model.getMsg());
                    }
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private void initViews() {
        userId = findViewById(R.id.user_id);
        userName = findViewById(R.id.user_name);
        uploadHeadPic = findViewById(R.id.upload_head_pic);
        registerBtn = findViewById(R.id.register);
        userList = findViewById(R.id.linkman_list);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        userList.setLayoutManager(manager);
    }
}